<?php
namespace SixShop\News\Controller\Admin;

use think\Request;
use think\facade\Validate;
use SixShop\News\Service\NewsCategoryServiceAdapter;

class CategoryController
{
    protected $service;

    public function __construct()
    {
        $this->service = new NewsCategoryServiceAdapter();
    }

    /**
     * 分类列表
     */
    public function index(Request $request)
    {
        $data = $this->service->getList();
        return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 分类详情
     */
    public function read($id)
    {
        $info = $this->service->getById($id);
        if (!$info) {
            return json(['code' => 404, 'msg' => '分类不存在']);
        }
        return json(['code' => 200, 'msg' => 'success', 'data' => $info]);
    }

    /**
     * 新增分类
     */
    public function create(Request $request)
    {
        $data = $request->only(['name', 'sort', 'status']);
        $validate = Validate::rule([
            'name' => 'require|max:64',
            'sort' => 'number',
            'status' => 'in:0,1',
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 422, 'msg' => $validate->getError()]);
        }
        $res = $this->service->create($data);
        return json(['code' => 200, 'msg' => '创建成功', 'data' => $res]);
    }

    /**
     * 编辑分类
     */
    public function update($id, Request $request)
    {
        $data = $request->only(['name', 'sort', 'status']);
        $validate = Validate::rule([
            'name' => 'require|max:64',
            'sort' => 'number',
            'status' => 'in:0,1',
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 422, 'msg' => $validate->getError()]);
        }
        $res = $this->service->update($id, $data);
        if (!$res) {
            return json(['code' => 404, 'msg' => '分类不存在']);
        }
        return json(['code' => 200, 'msg' => '更新成功', 'data' => $res]);
    }

    /**
     * 删除分类
     */
    public function delete($id)
    {
        $res = $this->service->delete($id);
        if (!$res) {
            return json(['code' => 404, 'msg' => '分类不存在']);
        }
        return json(['code' => 200, 'msg' => '删除成功']);
    }
} 